package com.gitee.feizns.quickstart.web.ex.impl;

import com.gitee.feizns.quickstart.domain.vo.Ret;
import com.gitee.feizns.quickstart.web.ex.ErrorCode;
import com.gitee.feizns.quickstart.web.ex.HttpException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;

/**
 * 将会改变响应状态码的Http异常
 * @author feizns
 * @since 2019/7/7
 */
public class HttpExceptionHandler extends AbstractExceptionHandler<HttpException> {

    /**
     * 在没有配置错误码的情况下，使用HTTP状态码 + 异常消息作为响应的业务错误码
     * @param e {@link HttpException}
     * @return {@link ResponseEntity}
     */
    @Override
    public ResponseEntity<Ret<?>> handle(HttpException e) {
        HttpStatus status = e.getStatus();
        ErrorCode errorCode = e.getErrorCode();
        Integer code = status.value();
        String msg = StringUtils.hasText(e.getMessage()) ? e.getMessage(): status.name();
        if ( errorCode != null ) {
            code = errorCode.getCode();
            msg = errorCode.getMsg();
        }
        return ResponseEntity.status(status).body(Ret.error(code, msg));
    }

}
